<template>
    <div class="container">
      <!-- 根据showDetail状态判断显示哪个部分 -->
      <div v-if="!showDetail">
        <!-- 原搜索栏部分 -->
        <div class="search-bar">
          <el-input placeholder="单据编码" v-model="page.DocumentCode" style="width: 300px;"/>
          <el-select v-model="page.DocumentStatus" placeholder="单据状态" clearable style="width: 300px;">
            <el-option label="开立" value="开立" />
            <el-option label="审核" value="审核" />
            <el-option label="退回" value="退回" />
          </el-select>
          <el-select v-model="page.BusinessStatus" placeholder="业务状态" clearable style="width: 300px;">
            <el-option label="正常" value="正常" />
            <el-option label="挂起" value="挂起" />
            <el-option label="手工关闭" value="手工关闭" />
            <el-option label="系统关闭" value="系统关闭" />
          </el-select>
          <el-date-picker
            v-model="page.BeginData"
            type="date"
            placeholder="开始日期"
            style="width: 150px;"
          />
          -
          <el-date-picker
            v-model="page.EndData"
            type="date"
            placeholder="结束日期"
            style="width: 150px;"
          />
          <el-button type="primary" @click="getOutSourcingOrderList()">搜索</el-button>
        </div>
        <!-- 原操作按钮部分 -->
        <div class="action-buttons" style="margin-top: 20px;">
          <el-button type="primary"  @click="showDetail = true">明细</el-button>
          <el-button type="primary" @click="getOutSourcingOrderListes()">查询所有</el-button>
          <el-button type="success" @click="TiaozhuanAdd()">新增</el-button>
          <el-button type="danger" @click="DeleteGetOutID(selectedIds)" >删除</el-button>
          <el-button type="warning" @click="daochu(selectedIds)" >导出</el-button>
          <!-- <el-button type="success" >审核</el-button>
          <el-button type="warning" >反审核</el-button> -->
        </div>
        <!-- 原表格部分 -->
        <el-table :data="tableData" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="documentCode" label="单据编码" />
          <el-table-column prop="documentDate" label="单据日期">
            <template v-slot="scope">
                {{scope.row.documentDate.substring(0,10)}}
            </template>
          </el-table-column>
          <el-table-column prop="createdBy" label="创建人" />
          <el-table-column prop="documentStatus" label="单据状态" />
          <el-table-column prop="businessType" label="业务类型" />
          <el-table-column prop="businessStatus" label="业务状态" />
          <el-table-column prop="auditDate" label="审核日期" >
            <template v-slot="scope">
               <p v-if="scope.row.auditDate!='1900-01-01T00:00:00'">{{scope.row.auditDate.substring(0,10)}}</p>
               <p v-else> </p> 
            </template>
          </el-table-column>
          <el-table-column prop="auditor" label="审核人" />
          <el-table-column label="操作">
            <template #default="scope">
                <el-button link type="success" size="small" @click="chakan(scope.row.id)" >查看</el-button>
            <el-button link type="primary" size="small" @click="updates(scope.row.id)">修改</el-button>
            <el-button link type="danger" size="small" @click="DeleteOut(scope.row.id)" >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
      v-model:current-page="page.pageindex"
      v-model:page-size="page.pagesize"
      :page-sizes="[15, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    />
      </div>
      <div v-else>
        <!-- 新搜索栏部分 -->
        <div class="search-bar">
          <el-input placeholder="销售订单号" v-model="detailFormData.salesOrderNo"style="width: 180px;" />
          <el-input placeholder="单据编码" v-model="detailFormData.documentCode"style="width: 180px;" />
          <el-input placeholder="物料编码" v-model="detailFormData.materialCode" style="width: 180px;"/>
          <el-input placeholder="物料名称" v-model="detailFormData.materialName" style="width: 180px;"/>
          <el-date-picker
            v-model="detailFormData.startDate"
            type="date"
            placeholder="开始日期"
            style="width: 150px;"
          />
          -
          <el-date-picker
            v-model="detailFormData.endDate"
            type="date"
            placeholder="结束日期"
            style="width: 150px;"
          />
          <el-button type="primary" @click="detailSearch">搜索</el-button>
        </div>
        <!-- 新操作按钮部分 -->
        <div class="action-buttons" style="margin-top: 20px;">
          <el-button type="primary"  @click="showDetail = false">单据</el-button>
          <el-button type="primary" >查询所有</el-button>
          <el-button type="success" >新增</el-button>
          <el-button type="warning"  @click="daochu(selectedIds)">导出</el-button>
        </div>
        <!-- 新表格部分 -->
        <el-table :data="detailTableData">
          <el-table-column prop="serialNumber" label="序号" />
          <el-table-column prop="salesOrderNo" label="销售单号" />
          <el-table-column prop="deliveryDate" label="订单交期" />
          <el-table-column prop="documentCode" label="单据编码" />
          <el-table-column prop="documentStatus" label="单据状态" />
          <el-table-column prop="materialName" label="物料名称" />
          <el-table-column prop="specification" label="规格" />
          <el-table-column prop="materialCode" label="物料编码" />
          <el-table-column prop="mainMeasurement" label="主计量" />
          <el-table-column prop="demandDate" label="需求日期" />
          <el-table-column prop="outsourcingQuantity" label="委外数量" />
          <el-table-column prop="arrivalQuantity" label="到货数量" />
        </el-table>
      </div>
    </div>
  </template>
  
  <script setup>
import axios from 'axios';
import { ref, reactive, onMounted } from 'vue';
import { ElMessage ,ElMessageBox} from 'element-plus';
import {useRoute,useRouter} from 'vue-router'
import { saveAs } from 'file-saver';
import {KongaUrl} from '@/axios/axiosHelp';
let router=useRouter();
  onMounted(()=>{
    getOutSourcingOrderList()
  })
  const page=reactive({
    pageindex:1,
    pagesize:15,
    DocumentCode:'',
    DocumentStatus:'',
    BusinessStatus:'',
    BeginData:'',
    EndData:'',
    totalpage:0,
    totalcount:0,
  })
  // 原表格数据
  const tableData = ref([]);
//查询单据方法
const getOutSourcingOrderList=()=>{
  KongaUrl({
        url:'/weiwaidu/api/OutSourc/QueryOutSourOrder',
        method:'get',
        params:{
            pageindex:page.pageindex,
            pagesize:page.pagesize,
            DocumentCode:page.DocumentCode,
            DocumentStatus:page.DocumentStatus,
            BusinessStatus:page.BusinessStatus,
            BeginData:page.BeginData,
            EndData:page.EndData,
        }
    })
    .then(res=>{
        if(res.data.code==101){
            tableData.value=res.data.list;
            console.log(tableData.value)
            page.totalcount=res.data.totalcount
            page.totalpage=res.data.totalpage
        }
    })
}
const getOutSourcingOrderListes=()=>{
  KongaUrl({
        url:'/weiwaidu/api/OutSourc/QueryOutSourOrder',
        method:'get',
        params:{
            pageindex:page.pageindex,
            pagesize:page.pagesize,
        }
    })
    .then(res=>{
        if(res.data.code==101){
            tableData.value=res.data.list;
            console.log(tableData.value)
            page.totalcount=res.data.totalcount
            page.totalpage=res.data.totalpage
        }
    })
}

  // 控制是否显示明细内容的状态
  const showDetail = ref(false)
  
  // 新的明细表单数据
  const detailFormData = ref({
    salesOrderNo: '',
    documentCode: '',
    materialCode: '',
    materialName: '',
    startDate: '',
    endDate: ''
  })
// 测试数据
const detailTableData = ref([
  {
    serialNumber: 1,
    salesOrderNo: 'SO-20231001-001',
    deliveryDate: '2023-10-15',
    documentCode: 'DOC-20231001-A1',
    documentStatus: '已提交',
    materialName: '不锈钢板材',
    specification: '304/2.0mm',
    materialCode: 'M-304-SS',
    mainMeasurement: '千克',
    demandDate: '2023-10-10',
    outsourcingQuantity: 1500,
    arrivalQuantity: 1200
  },
  {
    serialNumber: 2,
    salesOrderNo: 'SO-20231002-005',
    deliveryDate: '2023-10-18',
    documentCode: 'DOC-20231002-B2',
    documentStatus: '已审核',
    materialName: '铝合金型材',
    specification: '6061-T6',
    materialCode: 'M-AL-6061',
    mainMeasurement: '米',
    demandDate: '2023-10-12',
    outsourcingQuantity: 500,
    arrivalQuantity: 500
  },
  {
    serialNumber: 3,
    salesOrderNo: 'SO-20231003-008',
    deliveryDate: '2023-10-20',
    documentCode: 'DOC-20231003-C3',
    documentStatus: '待处理',
    materialName: 'PVC塑料粒子',
    specification: 'SG-5',
    materialCode: 'M-PVC-SG5',
    mainMeasurement: '吨',
    demandDate: '2023-10-15',
    outsourcingQuantity: 2000,
    arrivalQuantity: 0
  },
  {
    serialNumber: 4,
    salesOrderNo: 'SO-20231004-012',
    deliveryDate: '2023-10-22',
    documentCode: 'DOC-20231004-D4',
    documentStatus: '已关闭',
    materialName: '铜制阀门',
    specification: 'DN50/PN16',
    materialCode: 'M-CU-VALVE',
    mainMeasurement: '件',
    demandDate: '2023-10-18',
    outsourcingQuantity: 300,
    arrivalQuantity: 280
  }
])
  
  //翻页函数
  const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  page.pagesize=val;
  getOutSourcingOrderListes();
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  page.pageindex=val;
  getOutSourcingOrderListes();
}
const selectedIds = ref([])
// 选择项变化
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id)
  console.log('选中的数据', selectedIds.value)
}
  
  const detailSearch = () => {
    // 明细页面搜索逻辑，比如调用后端接口获取数据更新detailTableData
    console.log('执行明细搜索', detailFormData.value)
  }
//删除方法
const DeleteOut=(id)=>{
  ElMessageBox.confirm(
    '您确定要删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    KongaUrl({
    url:'/weiwaixie/api/Outsour/DeleteOutSourOrdere',
    method:'post',
    data:{
      id:id
    }
  })
  .then(res=>{
    if(res.data.code==101){
      getOutSourcingOrderListes();
      ElMessage.success("操作成功")
    }
  })
})
.catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}
// 批量删除操作
const DeleteGetOutID = (id) => {
  console.log('选中批量的数据', id.length)
  console.log('选中的数据', id)
  
  if(id.length === 0){
    ElMessage.error("请选择数据")
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${id.length} 条数据吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      // 修正后的请求方式
      const response = await KongaUrl({
        url: '/weiwaixie/api/Outsour/DeleteGetAllOrderID',
        method: 'post',
        data:{
          Id:id
        }
      })
      
      if(response.data.code == 101) {
        ElMessage.success('删除成功')
        // 刷新数据
        getOutSourcingOrderListes();
      } 
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  })
  .catch(() => {
    ElMessage.info('已取消删除')
  })
}
//跳转到新增页面方法
const TiaozhuanAdd=()=>{
  router.push("/AddOutSourOrder")
}

//修改方法
const updates=(id)=>{
  router.push({
    name:'UpdateOutSourOrder',
    query:{
      id:id
    }
  })
}
//查看详情方法
const chakan=(id)=>{
  router.push({
    name:'xiangqing',
    query:{
      id:id
    }
  })
}
//导出方法
const daochu = async () => {
    // 判断 selectedIds 的长度是否为 0
    if (selectedIds.value.length === 0) {
        ElMessage.warning('请选择要导出的数据');
        return;
    }

    try {
        const res = await KongaUrl.get('/weiwaidu/api/OutSourc/Daochuweiwai', {
            params: {
                // 将参数名改为 Id，与后端保持一致
                Id: selectedIds.value
            },
            paramsSerializer: (params) => {
                const parts = [];
                for (const key in params) {
                    if (Array.isArray(params[key])) {
                        params[key].forEach((value) => {
                            parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
                        });
                    } else {
                        parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
                    }
                }
                return parts.join('&');
            },
            responseType: 'blob'
        });
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        saveAs(blob, '委外订单列表.xlsx');
    } catch (error) {
        ElMessage.error('批量导出失败，请联系管理员');
        console.error('批量导出错误:', error);
    }
};    
  </script>
  
  <style scoped>
  .container {
    padding: 10px;
  }
  .search-bar {
    margin-bottom: 10px;
    display: flex;
    gap: 10px;
  }
  .action-buttons {
    margin-bottom: 10px;
    display: flex;
    gap: 10px;
  }
  </style>    